<?php

namespace App\Http\Controllers;

use App\Http\Business\PriceBusiness;
use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use App\Exceptions\PriceException;
use Illuminate\Support\Facades\Cache;

class PriceController extends Controller
{
    protected $_sign;
    protected $_areaNumber;
    protected $_goldAmount;
    protected $_business;
    const SELL_UNIT_AMOUNT = 1000;//出货的最小单位，一般为1000W
    const BUY_MIN_AMOUNT = 100;//最小采购数量,1771是50W，17uoo是200W 这里默认为100W

    public function __construct($priceBusiness = null)
    {
        $this->_business = is_null($priceBusiness) ? new PriceBusiness() : $priceBusiness;
    }

    /**
     * 得到采购价格 http://note.youdao.com/share/?token=27CCBCEB1EC343B1AD77E36F1F84CF08&gid=29320983
     * @return array
     */
    public function getBuyPrice()
    {
        $this->_checkInput();
        //验证是否小于采购最小数量
        $this->_goldAmount = max(self::BUY_MIN_AMOUNT, $this->_goldAmount);

        //每笔采购订单的金币量不能超过最大限制
        $orderMaxGoldAmount = config('app.price.orderBuyMaxGoldAmount');
        $this->_goldAmount = min($orderMaxGoldAmount, $this->_goldAmount);

        $res = $this->_business->getBuyPrice($this->_areaNumber, $this->_goldAmount);

        return $res;
    }

    /**
     * 得到出货价格 http://note.youdao.com/groupshare/?token=D768B67BE19147F18DA672D74AAD9C31&gid=29320983
     * @return array
     */
    public function getSellPrice()
    {
        $this->_checkInput();
        //出货数量必须为1000的整数倍
        if ($this->_goldAmount % self::SELL_UNIT_AMOUNT !== 0) {
            $this->_goldAmount = intval($this->_goldAmount / self::SELL_UNIT_AMOUNT) * self::SELL_UNIT_AMOUNT;
        }

        //如果出货数量小于最小出货单元，那么
        $this->_goldAmount = max(self::SELL_UNIT_AMOUNT, $this->_goldAmount);

        //每笔出货订单的金币量不能超过最大限制
        $orderMaxGoldAmount = config('app.price.orderSellMaxGoldAmount');
        $this->_goldAmount = min($orderMaxGoldAmount, $this->_goldAmount);

        $res = $this->_business->getSellPrice($this->_areaNumber, $this->_goldAmount);

        return $res;
    }

    /**
     *传入参数和签名校验
     * @throws PriceException
     */
    protected function _checkInput()
    {
        $sign = isset($_GET['sign']) ? $_GET['sign'] : null;
        $areaNumber = isset($_GET['areaNumber']) ? $_GET['areaNumber'] : null;
        $goldAmount = isset($_GET['goldAmount']) ? $_GET['goldAmount'] : null;

        //判断输入必传参数是否都有传入
        if (is_null($sign) || is_null($areaNumber) || is_null($goldAmount)) {
            throw new PriceException(403);
        }

        //首先验证签名，如果签名失败，那么直接返回
        if (!$this->_business->checkSign()) {
            throw new PriceException(402);
        }

        //判断输入格式是否正确
        if (!is_numeric($areaNumber) || !is_numeric($goldAmount)) {
            throw new PriceException(404);
        }

        $this->_sign = $sign;
        $this->_areaNumber = intval($areaNumber);
        $this->_goldAmount = intval($goldAmount);
    }
}
